package com.example.provider;

import com.example.anonation.AppLog;

import javax.annotation.Priority;
import javax.ws.rs.Consumes;
import javax.ws.rs.Priorities;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * Created by 01182800 on 2017/3/1.
 */
@AppLog
@Provider
@Priority(Priorities.USER)
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class LogFilter implements ClientRequestFilter, ContainerRequestFilter, ContainerResponseFilter, ClientResponseFilter {

    /**
     * 客户端过滤请求
     *
     * @param requestContext
     * @throws IOException
     */
    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        String method = requestContext.getMethod();
        String path = requestContext.getUri().getPath();
        System.out.println(String.format("LogFilter ClientRequestFilter: method = %s, path = %s", method, path));
    }

    /**
     * 服务端过滤请求
     *
     * @param requestContext
     * @throws IOException
     */
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String method = requestContext.getMethod();
        String path = requestContext.getUriInfo().getPath();
        System.out.println(String.format("LogFilter ContainerRequestFilter: method = %s, path = %s", method, path));
    }

    /**
     * 服务端过滤响应
     *
     * @param requestContext
     * @param responseContext
     * @throws IOException
     */
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        int status = responseContext.getStatus();
        System.out.println(String.format("LogFilter ContainerResponseFilter: status = %s", status));
    }

    /**
     * 客户端过滤响应
     * @param requestContext
     * @param responseContext
     * @throws IOException
     */
    @Override
    public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
        int status = responseContext.getStatus();
        System.out.println(String.format("LogFilter ContainerResponseFilter: status = %s", status));
    }
}
